package com.aaa.zm.filter;

import com.aaa.common.util.LoadPropertyUtil;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Properties;

/**
 * @author ：杨
 * @date ：Created in 2020/7/25 15:51
 * @description：
 * @modified By：
 * @version:
 */
@Component
public class IpFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 5;
    }

    @Override
    public boolean shouldFilter() {
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        HttpServletResponse response = currentContext.getResponse();
        String remoteAddr = request.getRemoteAddr();
        System.out.println("请求的IP为："+remoteAddr);
        Properties properties = LoadPropertyUtil.LoadPropertyByPath("filter_config.properties");
        if (properties.getProperty("filter_ip").contains(remoteAddr)){
            response.setCharacterEncoding("utf-8");
            try {
                response.sendError(403,"IP违法，禁止进入");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
